package com.ssd.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssd.api.couponAndIntegral.PointsRecordApi;
import com.ssd.api.couponAndIntegral.dto.PointsRecordDTO;
import com.ssd.api.product.ProductSkuApi;
import com.ssd.api.product.dto.SkuEntity;
import com.ssd.common.VMSystem;
import com.ssd.contract.VendoutResp;
import com.ssd.entity.OrderStatusResponse;
import com.ssd.mapper.OrderMapper;
import com.ssd.entity.OrderEntity;
import com.ssd.service.OrderDetailService;
import com.ssd.service.OrderService;
import com.ssd.view.BaseResponse;
import com.ssd.viewmodel.OrderDetailViewModel;
import com.ssd.viewmodel.OrderViewModel;
import com.ssd.viewmodel.Pager;
import com.ssd.vo.CancelOrderVO;
import com.ssd.vo.SkuInfoVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * OrderServiceImpl 类
 *
 * @title:
 * @requirement:
 * @ClassName:
 * @author:首雯静
 * @creationTime:2024-11-15/16:02
 * @version: 1.0
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {

    @Resource
    private ProductSkuApi productSkuApi;//远程调用对象-

    @Resource
    private OrderDetailService orderDetailService;

    @Resource
    private OrderService orderService;

    /**
     * 处理出货结果
     *
     * @param vendoutResp 出货请求参数
     * @return
     */
    @Override
    public boolean vendoutResult(VendoutResp vendoutResp) {
        return false;
    }

    @Resource
    private PointsRecordApi pointsRecordApi;
    /**
     * 支付完成
     *
     * @param orderEntity
     * @return
     */
    @Override
    public BaseResponse changeStatus(OrderEntity orderEntity) {

        UpdateWrapper<OrderEntity> uw = new UpdateWrapper<>();
        //修改订单状态
        uw.set("status", orderEntity.getStatus());
        //修改支付状态
        uw.set("pay_status", orderEntity.getPayStatus());
        //修改支付方式
        uw.set("pay_type", orderEntity.getPayType());
        //支付成功修改相应状态
        if (orderEntity.getPayStatus() == VMSystem.PAY_STATUS_PAYED) {
            uw.set("transactionId", orderEntity.getTransactionId());
            //如果有退款单号则改为支付成功状态
        } else if (orderEntity.getPayStatus() == VMSystem.PAY_STATUS_REFUNDING) {
            uw.set("refundNo", orderEntity.getRefundNo());
        }
        uw.set("update_time", orderEntity.getUpdateTime());
        uw.eq("order_no", orderEntity.getOrderNo());
        boolean update = this.update(uw);

        //根据订单id查询订单数据
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("order_no", orderEntity.getOrderNo());
        OrderEntity newOder = baseMapper.selectOne(qw);

        //封装新增积分dto类
        PointsRecordDTO prd = PointsRecordDTO.builder()
                .points(newOder.getAmount())//支付的金额
                .userId(Long.valueOf(newOder.getOpenId()))//用户id
                .remark("购买商品获得积分")//商品
                .createTime(LocalDateTimeUtil.now())
                .build();
        //远程调用新增积分
        pointsRecordApi.addRecord(prd);

        return new BaseResponse(update);
    }

    /**
     * 通过订单编号获取订单实体
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderViewModel getByOrderNo(String orderId) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("id", orderId);
        OrderEntity orderEntity = baseMapper.selectOne(qw);
        OrderViewModel orderViewModel = new OrderViewModel();
        orderViewModel.setId(orderEntity.getId());
        orderViewModel.setOrderNumber(orderEntity.getOrderNo());
        orderViewModel.setThirdNo(orderEntity.getThirdNo());
        orderViewModel.setInnerCode(orderEntity.getInnerCode());
        orderViewModel.setAddress(orderEntity.getAddr());
        orderViewModel.setOrderStatus(orderEntity.getStatus());
        orderViewModel.setStatus(orderEntity.getPayStatus() == 0 ? "待支付" : orderEntity.getPayStatus() == 1 ? "已支付" : orderEntity.getPayStatus() == 2 ? "退款中" : "退款完成");
        orderViewModel.setPayType(orderEntity.getPayType());
        orderViewModel.setAmount(orderEntity.getAmount());
        orderViewModel.setBill(orderEntity.getBill());
        orderViewModel.setRegionId(orderEntity.getRegionId());
        orderViewModel.setRegionName(orderEntity.getRegionName());
        orderViewModel.setBusinessId(orderEntity.getBusinessId());
        orderViewModel.setBusinessName(orderEntity.getBusinessName());
        orderViewModel.setOwnerId(orderEntity.getOwnerId());
        orderViewModel.setOpenId(orderEntity.getOpenId());
        orderViewModel.setCancelDesc(orderEntity.getCancelDesc());
        orderViewModel.setCreateTime(orderEntity.getCreateTime());
        orderViewModel.setUpdateTime(orderEntity.getUpdateTime());
        return orderViewModel;
    }

    @Override
    public OrderViewModel getByOrderNoA(String orderId) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("order_no", orderId);
        OrderEntity orderEntity = baseMapper.selectOne(qw);
        OrderViewModel orderViewModel = new OrderViewModel();
        orderViewModel.setId(orderEntity.getId());
        orderViewModel.setOrderNumber(orderEntity.getOrderNo());
        orderViewModel.setThirdNo(orderEntity.getThirdNo());
        orderViewModel.setInnerCode(orderEntity.getInnerCode());
        orderViewModel.setAddress(orderEntity.getAddr());
        orderViewModel.setOrderStatus(orderEntity.getStatus());
        orderViewModel.setStatus(orderEntity.getPayStatus() == 0 ? "待支付" : orderEntity.getPayStatus() == 1 ? "已支付" : orderEntity.getPayStatus() == 2 ? "退款中" : "退款完成");
        orderViewModel.setPayType(orderEntity.getPayType());
        orderViewModel.setAmount(orderEntity.getAmount());
        orderViewModel.setBill(orderEntity.getBill());
        orderViewModel.setRegionId(orderEntity.getRegionId());
        orderViewModel.setRegionName(orderEntity.getRegionName());
        orderViewModel.setBusinessId(orderEntity.getBusinessId());
        orderViewModel.setBusinessName(orderEntity.getBusinessName());
        orderViewModel.setOwnerId(orderEntity.getOwnerId());
        orderViewModel.setOpenId(orderEntity.getOpenId());
        orderViewModel.setCancelDesc(orderEntity.getCancelDesc());
        orderViewModel.setCreateTime(orderEntity.getCreateTime());
        orderViewModel.setUpdateTime(orderEntity.getUpdateTime());
        return orderViewModel;
    }

    @Override
    public OrderStatusResponse getStatusByOrderNo(String orderNo) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("order_no", orderNo);
        OrderEntity orderEntity = baseMapper.selectOne(qw);
        OrderStatusResponse orderStatusResponse = new OrderStatusResponse();
        orderStatusResponse.setOrderNo(orderEntity.getOrderNo());
        orderStatusResponse.setStatus(String.valueOf(orderEntity.getPayStatus()));
        orderStatusResponse.setAmount(BigDecimal.valueOf(orderEntity.getAmount()));
        return orderStatusResponse;
    }

    @Override
    public List<com.ssd.api.order.dto.OrderDetailViewModel> getListByOrderNo(String orderId) {
        return orderDetailService.getListByOrderId1(Long.valueOf(orderId));
    }

    @Override
    public String getByTransactionId(String transactionId) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("transactionId", transactionId);
        OrderEntity orderEntity = baseMapper.selectOne(qw);
        return String.valueOf(orderEntity.getId());
    }

    /**
     * 取消订单
     *
     * @param cancelOrderVO
     * @return
     */
    @Override
    public BaseResponse cancel(CancelOrderVO cancelOrderVO) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.eq("order_id", cancelOrderVO.getOrderId());
        OrderEntity orderEntity = baseMapper.selectOne(qw);
        //只能取消新建状态的订单
        if (orderEntity.getStatus() == VMSystem.ORDER_STATUS_VENDOUT_SUCCESS) {
            return new BaseResponse(false, "该订单已出货，不能取消");
            //退款中或退款完成的订单不能取消
        } else if (orderEntity.getPayStatus() == VMSystem.PAY_STATUS_REFUNDING || orderEntity.getPayStatus() == VMSystem.PAY_STATUS_REFUNDIED) {
            return new BaseResponse(false, "正在处理订单，请勿重复操作");
        } else {
            orderEntity.setPayStatus(2);
            //添加取消原因
            orderEntity.setCancelDesc(cancelOrderVO.getDesc());
            orderEntity.setUpdateTime(LocalDateTime.now());
            //修改数据库
            boolean update = this.update(orderEntity, qw);
            return new BaseResponse(update);
        }
    }

    /**
     * 订单搜索
     *
     * @param pageIndex
     * @param pageSize
     * @param openId
     * @return
     */
    @Override
    public List<OrderViewModel> getListByOpenId(Integer pageIndex, Integer pageSize, String openId) {
        // 创建分页对象
        Page<OrderEntity> page = new Page<>(pageIndex, pageSize);
        // 创建查询条件
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        //构建查询条件
        if (!openId.isEmpty()) {
            queryWrapper.eq("open_id", openId);
        }
        // 执行分页查询
        IPage<OrderEntity> orderPage = baseMapper.selectPage(page, queryWrapper);
        List<OrderEntity> orderList = orderPage.getRecords();
        List<OrderViewModel> orderViewModels = new ArrayList<>();
        //转换为viewModel对象输出
        for (OrderEntity orderEntity : orderList) {
            OrderViewModel orderViewModel = new OrderViewModel();
            orderViewModel.setId(orderEntity.getId());
            orderViewModel.setOrderNumber(orderEntity.getOrderNo());
            orderViewModel.setThirdNo(orderEntity.getThirdNo());
            orderViewModel.setInnerCode(orderEntity.getInnerCode());
            orderViewModel.setAddress(orderEntity.getAddr());
            orderViewModel.setOrderStatus(orderEntity.getStatus());
            orderViewModel.setStatus(orderEntity.getPayStatus() == 0 ? "待支付" : orderEntity.getPayStatus() == 1 ? "已支付" : orderEntity.getPayStatus() == 2 ? "退款中" : "退款完成");
            orderViewModel.setPayType(orderEntity.getPayType());
            orderViewModel.setAmount(orderEntity.getAmount());
            orderViewModel.setBill(orderEntity.getBill());
            orderViewModel.setRegionId(orderEntity.getRegionId());
            orderViewModel.setRegionName(orderEntity.getRegionName());
            orderViewModel.setBusinessId(orderEntity.getBusinessId());
            orderViewModel.setBusinessName(orderEntity.getBusinessName());
            orderViewModel.setOwnerId(orderEntity.getOwnerId());
            orderViewModel.setOpenId(orderEntity.getOpenId());
            orderViewModel.setCancelDesc(orderEntity.getCancelDesc());
            orderViewModel.setCreateTime(orderEntity.getCreateTime());
            orderViewModel.setUpdateTime(orderEntity.getUpdateTime());
            orderViewModels.add(orderViewModel);
        }
        return orderViewModels;
    }

    @Override
    public Pager<OrderEntity> search(Integer pageIndex, Integer pageSize, String orderNo, LocalDate start, LocalDate end) {
        //分页插件
        Page<OrderEntity> page = new Page<>(pageIndex, pageSize);
        //创建查询条件
        QueryWrapper<OrderEntity> qw = Wrappers.query();
        if (!orderNo.isEmpty()) {
            qw.like("order_no", orderNo);
        }
        if (start != null) {
            qw.gt("create_time", start);
        }
        if (end != null) {
            qw.lt("create_time", end);
        }
        qw.orderByDesc("create_time");//根据时间倒序
        Page<OrderEntity> orderPage = this.page(page, qw);
        Pager<OrderEntity> orderPager = Pager.build(orderPage);
        return orderPager;
    }

    /**
     * 获取商圈下销量最好的10个商品
     *
     * @param businessId
     * @return
     */
    @Override
    public List<Long> getTop10Sku(Integer businessId) {
        return baseMapper.getTop10Sku(businessId);
    }

    /**
     * 获取一定时间范围之内的金额
     *
     * @param partnerId
     * @param start
     * @param end
     * @return
     */
    @Override
    public Long getAmount(Integer partnerId, String innerCode, LocalDateTime start, LocalDateTime end) {
        QueryWrapper qw = Wrappers.query();
        qw.eq("inner_code", innerCode);
        qw.eq("owner_id", partnerId);
        qw.between("create_time", start, end);
        List<OrderEntity> list = baseMapper.selectList(qw);
        return null;
    }

    /**
     * 生成订单
     *
     * @param openId
     * @param innerCode
     * @param amount
     * @return
     */
    @Override
    public Long createOrder(String openId, String innerCode, Integer amount,String productOrderNo,String addr) {
        OrderEntity orderEntity = new OrderEntity();
        //生成订单号
        long orderNo = Long.parseLong(productOrderNo);
        orderEntity.setOrderNo(String.valueOf(orderNo));
        orderEntity.setInnerCode(innerCode);
        orderEntity.setPayStatus(0);
        orderEntity.setStatus(0);
        orderEntity.setAmount(amount);
        orderEntity.setOpenId(openId);
        orderEntity.setCreateTime(LocalDateTime.now());
        orderEntity.setAddr(addr);
        //添加商品到数据库
        this.save(orderEntity);
        //返回主键
        return orderEntity.getId();
    }

    @Override
    public Integer computeAmount(List<SkuInfoVO> skuList) {
        Integer amount = 0;
        // 调用商品服务获取信息
        for (SkuInfoVO skuInfoVO : skuList) {
            BaseResponse<SkuEntity> skuById1 = productSkuApi.getSkuById1(skuInfoVO.getSkuId());
            Integer price = skuById1.getData().getPrice();
            //计算总金额
            amount += price * skuInfoVO.getQuantity();
        }
        return amount;
    }
}
